package com.powernode.reflect;

import com.powernode.reflect.pojo.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;

/**
 *
 * 反射 ：
 *      构造方法
 * @author : zjj
 * @date : 2022/9/22 14:56
 */
public class TestReflect07 {

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
//        testGetAllConstruct();
        testExecuteConstruct();
    }

    /**
     * 执行构造器
     */
    public static void testExecuteConstruct() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class personClass = generateClass();
        Constructor constructor = personClass.getConstructor(String.class, String.class, Integer.class);
        String username = "张三";
        String password = "root";
        Integer age = 10;
        Person person = (Person) constructor.newInstance(username, password,age);
        System.out.println(person);
    }

    /**
     * 拿到所有的构造方法
     */
    public static void testGetAllConstruct(){
        Class personClass = generateClass();

        Constructor[] constructors = personClass.getConstructors();
        for (Constructor construct : constructors) {
            // 名称
            System.out.println("构造器名称："  + construct.getName());
            //修饰符
            int modifiers = construct.getModifiers();
            System.out.println(Modifier.toString(modifiers));
            // 参数
            Parameter[] parameters = construct.getParameters();
            for (Parameter parameter : parameters) {
                System.out.println("\t参数类型：" + parameter.getType().getName());
                System.out.println("\t参数名称："+parameter.getName());
            }
        }

    }

    public static Class generateClass(){
        Class personClass = null;
        try {
            personClass = Class.forName("com.powernode.reflect.pojo.Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return personClass;
    }
}
